package test05;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

// 任务事件类
class TaskEvent {
    private String taskId;
    private String eventType; // "PROGRESS", "COMPLETED", "FAILED"
    private Date timestamp;
    private String currentStage;
    private Object data;
    private String errorMsg;

    public TaskEvent(String taskId, String eventType, String currentStage, Object data) {
        this.taskId = taskId;
        this.eventType = eventType;
        this.timestamp = new Date();
        this.currentStage = currentStage;
        this.data = data;
    }

    public TaskEvent(String taskId, String eventType, String currentStage, String errorMsg) {
        this.taskId = taskId;
        this.eventType = eventType;
        this.timestamp = new Date();
        this.currentStage = currentStage;
        this.errorMsg = errorMsg;
    }

    // Getters
    public String getTaskId() { return taskId; }
    public String getEventType() { return eventType; }
    public Date getTimestamp() { return timestamp; }
    public String getCurrentStage() { return currentStage; }
    public Object getData() { return data; }
    public String getErrorMsg() { return errorMsg; }

    @Override
    public String toString() {
        return String.format("TaskEvent{taskId='%s', eventType='%s', stage='%s', timestamp=%s}",
                taskId, eventType, currentStage, timestamp);
    }
}

// 观察者接口
interface AgentObserver {
    void onTaskProgress(TaskEvent event);
    void onTaskCompleted(TaskEvent event);
    void onTaskFailed(TaskEvent event);
}

// 主题接口
interface TaskCoordinator {
    void registerObserver(AgentObserver observer);
    void removeObserver(AgentObserver observer);
    void notifyObservers(TaskEvent event);
}

// 具体主题实现
class DefaultTaskCoordinator implements TaskCoordinator {
    private List<AgentObserver> observers = new CopyOnWriteArrayList<>();
    private String currentTaskId;
    private String currentStage;
    private Object taskData;

    @Override
    public void registerObserver(AgentObserver observer) {
        if (!observers.contains(observer)) {
            observers.add(observer);
            System.out.println("注册观察者: " + observer.getClass().getSimpleName());
        }
    }

    @Override
    public void removeObserver(AgentObserver observer) {
        observers.remove(observer);
        System.out.println("移除观察者: " + observer.getClass().getSimpleName());
    }

    @Override
    public void notifyObservers(TaskEvent event) {
        System.out.println("\n=== 通知观察者: " + event + " ===");
        for (AgentObserver observer : observers) {
            try {
                switch (event.getEventType()) {
                    case "PROGRESS":
                        observer.onTaskProgress(event);
                        break;
                    case "COMPLETED":
                        observer.onTaskCompleted(event);
                        break;
                    case "FAILED":
                        observer.onTaskFailed(event);
                        break;
                }
            } catch (Exception e) {
                System.err.println("观察者处理事件时出错: " + observer.getClass().getSimpleName() + " - " + e.getMessage());
            }
        }
    }

    // 业务方法
    public void startTask(String taskId, Object initialData) {
        this.currentTaskId = taskId;
        this.currentStage = "INITIALIZED";
        this.taskData = initialData;

        System.out.println("\n🚀 开始任务: " + taskId);
        TaskEvent event = new TaskEvent(taskId, "PROGRESS", currentStage, initialData);
        notifyObservers(event);
    }

    public void updateProgress(String stage, Object data) {
        this.currentStage = stage;
        this.taskData = data;

        System.out.println("\n📊 更新进度: " + stage);
        TaskEvent event = new TaskEvent(currentTaskId, "PROGRESS", stage, data);
        notifyObservers(event);
    }

    public void completeTask(Object result) {
        System.out.println("\n✅ 任务完成");
        TaskEvent event = new TaskEvent(currentTaskId, "COMPLETED", "COMPLETED", result);
        notifyObservers(event);
    }

    public void failTask(String errorMsg) {
        System.out.println("\n❌ 任务失败: " + errorMsg);
        TaskEvent event = new TaskEvent(currentTaskId, "FAILED", currentStage, errorMsg);
        notifyObservers(event);
    }

    // Getters
    public String getCurrentTaskId() { return currentTaskId; }
    public String getCurrentStage() { return currentStage; }
    public Object getTaskData() { return taskData; }
}

// 具体观察者实现
class DataPreprocessAgent implements AgentObserver {
    private String agentName = "DataPreprocessAgent";

    @Override
    public void onTaskProgress(TaskEvent event) {
        if ("INITIALIZED".equals(event.getCurrentStage())) {
            System.out.println(agentName + ": 🧹 开始数据预处理...");
            try {
                // 模拟数据处理
                Thread.sleep(1000);
                System.out.println(agentName + ": ✅ 数据预处理完成");

                // 通知协调者进入下一阶段
                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.updateProgress("DATA_PREPROCESSED", "清洗后的数据集");
                }
            } catch (Exception e) {
                System.out.println(agentName + ": ❌ 数据预处理失败 - " + e.getMessage());
                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.failTask("数据预处理失败: " + e.getMessage());
                }
            }
        }
    }

    @Override
    public void onTaskCompleted(TaskEvent event) {
        System.out.println(agentName + ": 📨 收到任务完成通知");
    }

    @Override
    public void onTaskFailed(TaskEvent event) {
        System.out.println(agentName + ": ⚠️ 收到任务失败通知 - " + event.getErrorMsg());
    }
}

class AnalysisEngineAgent implements AgentObserver {
    private String agentName = "AnalysisEngineAgent";

    @Override
    public void onTaskProgress(TaskEvent event) {
        if ("DATA_PREPROCESSED".equals(event.getCurrentStage())) {
            System.out.println(agentName + ": 🔍 开始数据分析...");
            try {
                Thread.sleep(1500);
                System.out.println(agentName + ": ✅ 数据分析完成");

                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.updateProgress("ANALYSIS_COMPLETED", "分析结果和洞察");
                }
            } catch (Exception e) {
                System.out.println(agentName + ": ❌ 数据分析失败 - " + e.getMessage());
                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.failTask("数据分析失败: " + e.getMessage());
                }
            }
        }
    }

    @Override
    public void onTaskCompleted(TaskEvent event) {
        System.out.println(agentName + ": 📨 收到任务完成通知");
    }

    @Override
    public void onTaskFailed(TaskEvent event) {
        System.out.println(agentName + ": ⚠️ 收到任务失败通知 - " + event.getErrorMsg());
    }
}

class VisualizationAgent implements AgentObserver {
    private String agentName = "VisualizationAgent";

    @Override
    public void onTaskProgress(TaskEvent event) {
        if ("ANALYSIS_COMPLETED".equals(event.getCurrentStage())) {
            System.out.println(agentName + ": 📊 开始生成图表...");
            try {
                Thread.sleep(800);
                System.out.println(agentName + ": ✅ 图表生成完成");

                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.updateProgress("VISUALIZATION_COMPLETED", "生成的图表集合");
                }
            } catch (Exception e) {
                System.out.println(agentName + ": ❌ 图表生成失败 - " + e.getMessage());
                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.failTask("图表生成失败: " + e.getMessage());
                }
            }
        }
    }

    @Override
    public void onTaskCompleted(TaskEvent event) {
        System.out.println(agentName + ": 📨 收到任务完成通知");
    }

    @Override
    public void onTaskFailed(TaskEvent event) {
        System.out.println(agentName + ": ⚠️ 收到任务失败通知 - " + event.getErrorMsg());
    }
}

class ReportGenerationAgent implements AgentObserver {
    private String agentName = "ReportGenerationAgent";

    @Override
    public void onTaskProgress(TaskEvent event) {
        if ("VISUALIZATION_COMPLETED".equals(event.getCurrentStage())) {
            System.out.println(agentName + ": 📝 开始生成最终报告...");
            try {
                Thread.sleep(1200);
                String report = "📋 数据分析报告\n" +
                        "================\n" +
                        "- 数据预处理: 已完成\n" +
                        "- 分析结果: 发现重要趋势\n" +
                        "- 可视化: 生成5个关键图表\n" +
                        "- 结论: 数据质量良好，建议进一步分析";
                System.out.println(agentName + ": ✅ 报告生成完成");

                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.completeTask(report);
                }
            } catch (Exception e) {
                System.out.println(agentName + ": ❌ 报告生成失败 - " + e.getMessage());
                if (event.getData() instanceof DefaultTaskCoordinator) {
                    DefaultTaskCoordinator coordinator = (DefaultTaskCoordinator) event.getData();
                    coordinator.failTask("报告生成失败: " + e.getMessage());
                }
            }
        }
    }

    @Override
    public void onTaskCompleted(TaskEvent event) {
        System.out.println(agentName + ": 🎉 任务完成！最终结果:\n" + event.getData());
    }

    @Override
    public void onTaskFailed(TaskEvent event) {
        System.out.println(agentName + ": ⚠️ 收到任务失败通知 - " + event.getErrorMsg());
    }
}

// 客户端演示代码
public class AICoordinationSystem {
    public static void main(String[] args) {
        System.out.println("🤖 AI智能体任务协同系统 - 观察者模式演示\n");

        // 创建任务协调者
        DefaultTaskCoordinator coordinator = new DefaultTaskCoordinator();

        // 创建并注册各个智能体
        DataPreprocessAgent dataAgent = new DataPreprocessAgent();
        AnalysisEngineAgent analysisAgent = new AnalysisEngineAgent();
        VisualizationAgent visualizationAgent = new VisualizationAgent();
        ReportGenerationAgent reportAgent = new ReportGenerationAgent();

        coordinator.registerObserver(dataAgent);
        coordinator.registerObserver(analysisAgent);
        coordinator.registerObserver(visualizationAgent);
        coordinator.registerObserver(reportAgent);

        // 启动任务
        coordinator.startTask("TASK_2024_001", coordinator);

        // 等待任务完成
        try {
            Thread.sleep(5000);
            System.out.println("\n✨ 所有任务执行完成！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 演示动态添加观察者
        System.out.println("\n--- 演示动态扩展 ---");
        AgentObserver newAgent = new AgentObserver() {
            @Override
            public void onTaskProgress(TaskEvent event) {
                System.out.println("🆕 新智能体: 观察到进度更新 - " + event.getCurrentStage());
            }

            @Override
            public void onTaskCompleted(TaskEvent event) {
                System.out.println("🆕 新智能体: 观察到任务完成");
            }

            @Override
            public void onTaskFailed(TaskEvent event) {
                System.out.println("🆕 新智能体: 观察到任务失败");
            }
        };

        coordinator.registerObserver(newAgent);
        coordinator.startTask("TASK_2024_002", coordinator);
    }
}